#ifndef PRINTFLOG_H
#define PRINTFLOG_H

#include <stdio.h>  //FILE* fopen(), fclose(), fprintf(), perrror()
#include <string.h> //strcat()-字符串拼接   strftime()-时间格式化
#include <time.h>   //time(), localtime_r(),struct tm, time_t

// 检查命令行参数数量是否符合预期
#define ARGS_CHECK(argc, expected) \
    do { \
        if ((argc) != (expected)) { \
            fprintf(stderr, "args num error!\n"); \
            exit(1); \
        } \
    } while (0)                      

// 检查返回值是否是错误标记,若是则打印msg和错误信息
#define ERROR_CHECK(ret, error_flag, msg) \
    do { \
        if ((ret) == (error_flag)) { \
            perror(msg); \
            exit(1); \
        } \
    } while (0)

#define printfLog(username, message, line, file, func) do { \
    /* 获取当前时间 */ \
    time_t now = time(NULL); \
    struct tm tm_info; \
    localtime_r(&now, &tm_info); \
    \
    /* 格式化时间字符串 */ \
    char time_str[20]; \
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", &tm_info); \
    \
    /* 打开日志文件 */ \
    FILE *log_file = fopen("messageInf.log", "a"); \
    if (!log_file) { \
        perror("Failed to open log file"); \
    } else { \
        /* 写入日志信息 */ \
        fprintf(log_file, "[%s][User: %s] %s (Location: %s:%d %s)\n", \
                time_str, \
                (username) ? (username) : "unknown", \
                (message), \
                (file), \
                (line), \
                (func)); \
        fclose(log_file); \
    } \
} while(0)

#define LOG(username, message) printfLog((username), (message), __LINE__, __FILE__, __func__)

#endif

